﻿using System;
using System.Collections.Generic;
using System.Linq;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;

namespace DotnetUtil.Json
{
    public static class JsonHelper
    {
        private static readonly JsonSerializerSettings SerializerSettings;

        static JsonHelper()
        {
            SerializerSettings = new JsonSerializerSettings
            {
                MissingMemberHandling = MissingMemberHandling.Ignore,
                NullValueHandling = NullValueHandling.Ignore,
                ReferenceLoopHandling = ReferenceLoopHandling.Ignore
            };
            SerializerSettings.Converters.Add(new IsoDateTimeConverter
                { DateTimeFormat = @"yyyy-MM-dd HH:mm:ss" });
        }

        /// <summary>
        /// 将指定的对象序列化成 JSON 数据。
        /// </summary>
        /// <param name="value">要序列化的对象。</param>
        /// <param name="ignores">要忽略的属性列表</param>
        /// <returns>JSON 格式数据</returns>
        public static string SerializeObject(object value, List<string> ignores = null)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            SerializerSettings.ContractResolver = ignores != null && ignores.Any()
                ? new ExcludePropertiesContractResolver(ignores)
                : null;
            return JsonConvert.SerializeObject(value, Formatting.None, SerializerSettings);
        }

        /// <summary>
        /// 将指定的 JSON 数据反序列化成指定对象。
        /// </summary>
        /// <typeparam name="T">对象类型。</typeparam>
        /// <param name="value">JSON 数据。</param>
        /// <param name="ignores">要忽略的属性列表</param>
        /// <returns>指定类型的对象</returns>
        public static T DeserializeObject<T>(string value, List<string> ignores = null)
        {
            if (string.IsNullOrWhiteSpace(value))
            {
                throw new ArgumentNullException(nameof(value));
            }

            SerializerSettings.ContractResolver = ignores != null && ignores.Any()
                ? new ExcludePropertiesContractResolver(ignores)
                : null;
            return JsonConvert.DeserializeObject<T>(value, SerializerSettings);
        }
    }
}
